<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<title>RGB转HEX</title>
<style>
.center{
    text-align: center;
}
.btn-row{
    padding:0 15px;
}
.btn-row .col-md-6{
    border:1px solid #ddd;
    padding:10px;
}
</style>
</head>
<body>
    <div class="container" id="app">
        <h3 class="center">在线颜色转换 RGB 转 HEX</h3>
        <div class="form">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label>RGB颜色值：</label>
                        <input type="text" class="form-control" v-model="rgb">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label>HEX 16进制：</label>
                        <input type="text" class="form-control" v-model="color">
                    </div>
                    <div class="form-group">
                        <label>颜色选择：</label>
                        <input type="color" class="form-control" v-model="color">
                    </div>
                </div>
            </div>
            <div class="row center btn-row">
                <div class="col-md-6">
                    <button class="btn btn-default" type="button" @click="rgb2hex">RGB 转 HEX</button>
                </div>
                <div class="col-md-6">
                    <button class="btn btn-default" type="button" @click="hex2rgb">HEX 转 RGB</button>
                </div>
            </div>
          
        </div>
    </div>
</body>
</html>
<script src="https://cdn.bootcss.com/vue/2.3.3/vue.min.js"></script>
<script>
new Vue({
    el:"#app",
    data:{
        rgb:"",
        color:"",
        type:1,//1 rgb2hex 2 hex2rgb
    },
    created(){
        var rgb=[];
        for(var i=0;i<3;i++){
            rgb.push(this.rand(0,255));
        }
        this.rgb=rgb.join(",");
        this.rgb2hex();
    },
    methods:{
        rand(min,max){
            return Math.round(min+Math.random()*(max-min))
        },
        hex(str){
          var num=parseInt(str).toString(16);
          return num.length<2?"0"+num:num;
        },
        hex2rgb(){
            var re=[];
            for(var i=1;i<6;i++){
                if(i%2==1){
                    let item=this.color.substr(i,2);
                    re.push(parseInt(item,16));
                }
            }
            this.rgb="rgb("+re[0]+","+re[1]+","+re[2]+")";
        },
        rgb2hex(){
            var re=this.rgb.match(/\d+/g);
            if(re.length!=3) return;
            var hex="#"+this.hex(re[0])+this.hex(re[1])+this.hex(re[2]);
            this.color=hex;
        }
    }
})
</script>